package com.niit.session21;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;

import com.niit.session20.JDBCUtils;

public class ATM {
	public static void main(String[] args) {
		Connection conn = JDBCUtils.getConn();
		try {
//			关闭自动的事务提交
			conn.setAutoCommit(false);
			Statement statement = conn.createStatement();
			int update = statement.executeUpdate("update user set balance = balance -500 where id = 1");
//			在转账过程中发生异常，如果设置了手动的事务提交，发送异常之后，前面的更新不会生效
//			System.out.println(1/0);
			Statement statement1 = conn.createStatement();
			int update1 = statement1.executeUpdate("update user set balance = balance +500 where id = 2");
//			设置保存点
			Savepoint savepoint = conn.setSavepoint();
			Statement statement2 = conn.createStatement();
			int update2 = statement2.executeUpdate("update user set balance = balance -1 where id = 1");
//			回滚到指定保存点
			conn.rollback(savepoint);
			
			if(update> 0 && update1 >0) {
				System.out.println("转账成功！");
//				如果关闭了自动的事务提交，需要手动提交事务，否则所有更新操作都不会生效
				conn.commit();
			}else {
				System.out.println("转账失败！");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

}
